<?php

$this->page_template = null;
if (isset($_FILES['_f_upload_file_']) && $_FILES['_f_upload_file_']['error'] === 0) {
	$file = $_FILES['_f_upload_file_'];
	$type = $file['type'];
	$temp_path = f()->upload()->temp_path;
	$dir = f()->base_path.$temp_path;
	if (!file_exists($dir)) mkdir($dir,0777,true);	
	// create file id
	$id = uniqid('',false);
	// process file extension
	$dot_pos = strrpos($file['name'],'.');	
	if ($dot_pos === false) {
		$ext = '';
		$name = $file['name'];
	} else {
		$ext = substr($file['name'],$dot_pos);
		$name = substr($file['name'],0,$dot_pos);
	}
	// normalize file name
	$name = iconv("UTF-8", "us-ascii//TRANSLIT",$name);
	$name = preg_replace('/[^\w\d\s\-_]/m','',$name);
	$name = preg_replace('/[\s]/','_',$name).$ext;
	$ext = substr($ext,1);
	// TODO: case insensitive file systems
	if(!isset($_SESSION)) session_start();
	$_SESSION['_f_upload_file_'.$id] = array(
		'id' => $id,
		'name' => $name,
		'ext' => $ext,
		'type' => $type,
		'path' => $dir.'/'.$id,
	);
 	move_uploaded_file($file['tmp_name'],$dir.'/'.$id);
	echo '{ "error": false, "id": "'.$id.'", "ext": "'.$ext.
		'", "temp_file": "'.$this->url_base.'/'.$temp_path.'/'.$id.
		'", "type": "'.$type.'" }';
} else {
	echo '{ "error": true, "errorMessage": "Internal error" }';
}
